package com.ic.loan.fragment

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.GsonUtils
import com.gyf.immersionbar.ktx.immersionBar
import com.ic.loan.R
import com.ic.loan.bean.KeFu
import com.ic.loan.http.ApiUrl
import com.ic.loan.http.HttpUtils
import com.ic.loan.http.ResultListener
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import kotlinx.android.synthetic.main.fragment_customer.view.*
import java.lang.Exception


class CustomerFragment : Fragment() {
    private var loadingView: LoadingPopupView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        immersionBar {
            statusBarDarkFont(true)
        }
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_customer, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadingView = XPopup.Builder(requireContext()).asLoading()
        view.tvBtn.setOnClickListener {
            getKeFu()
        }
    }

    fun showLoading(){
        loadingView?.show()
    }

    fun hintLoading(){
        loadingView?.dismiss()
    }

    private fun getKeFu() {
        showLoading()
        HttpUtils.postOkGo(mutableMapOf(
            "timestamp" to System.currentTimeMillis() / 1000,
            "stable" to 1,
        ),
            ApiUrl.POST_KEFU,object : ResultListener() {
            override fun onSucceeded(json: String?) {
                try {
                    val kefu = GsonUtils.fromJson<KeFu>(json, KeFu::class.java)
                    val uri = Uri.parse("http://Wa.me/${kefu.kefu}")
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }catch (e: Exception){

                }
            }

            override fun onLoadFinish() {
                hintLoading()
            }
        })
    }


    companion object {
        @JvmStatic
        fun newInstance() = CustomerFragment()
    }
}